package leihua.crm.workbench.web.controller;
import leihua.crm.commons.contants.Contants;
import leihua.crm.commons.domain.ReturnObject;
import leihua.crm.commons.utils.DateUtils;
import leihua.crm.commons.utils.HSSFUtils;
import leihua.crm.commons.utils.UUIDUtils;
import leihua.crm.settings.domain.User;
import leihua.crm.settings.service.UserService;
import leihua.crm.workbench.domain.Activity;
import leihua.crm.workbench.domain.ActivityRemark;
import leihua.crm.workbench.service.ActivityRemarkService;
import leihua.crm.workbench.service.ActivityService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
 * @Author leiHua
 * @Date 2022/10/5 21:14
 */
@Controller
public class ActivityController {
    @Autowired
    private UserService userService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityRemarkService activityRemarkService;

    @RequestMapping("/workbench/activity/index.do")
    public String index(HttpServletRequest request) {
        List<User> userList = userService.queryAllUsers();
        request.setAttribute("userList", userList);
        return "workbench/activity/index";
    }

    //
    @RequestMapping("/workbench/activity/saveCreateActivity.do")
    @ResponseBody
    public Object saveCreateActivity(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(Contants.SESSION_USER);
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formateDateTime(new Date()));
        activity.setCreateBy(user.getId());
        ReturnObject returnObject = new ReturnObject();

        try {
            int result = activityService.saveCreateActivity(activity);
            if (result > 0) {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙请稍后");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙请稍后");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/queryActivityByConditionForPage.do")
    @ResponseBody
    public Object queryActivityByConditionForPage(String name, String owner, String startDate,
                                                  String endDate, int pageNo, int pageSize) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);
        map.put("owner", owner);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("beginNo", (pageNo - 1) * pageSize);   //beginNo :开始的条数    pageNo:页数
        map.put("pageSize", pageSize);

        List<Activity> activityList = activityService.queryActivityByConditionForPage(map);
        int totalRows = activityService.queryCountOfActivityByCondition(map);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("activityList", activityList);
        resultMap.put("totalRows", totalRows);
        resultMap.put("code",'1');
        return resultMap;

    }

    @RequestMapping("/workbench/activity/deleteActivityIds")
    @ResponseBody
    public Object deleteActivityIds(String[] id) {
        ReturnObject returnObject = new ReturnObject();

        try {
            int result = activityService.deleteActivityByids(id);
            if (result > 0) {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("请联系管理员");
            }
        } catch (Exception e) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("请联系管理员");
            e.printStackTrace();
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/queryActivityById.do")
    @ResponseBody
    public Object queryActivityById(String id) {
        Activity activity = activityService.queryActivityById(id);
        return activity;
    }

    @RequestMapping("/workbench/activity/savaEditActivity.do")
    @ResponseBody
    public Object savaEditActivity(Activity activity, HttpServletRequest request) {
        ReturnObject returnObject = new ReturnObject();
        String editTime = DateUtils.formateDateTime(new Date());
        activity.setEditTime(editTime);
        User user = (User) request.getSession().getAttribute(Contants.SESSION_USER);
        activity.setEditBy(user.getId());
        try {
            int result = activityService.saveEditActivity(activity);
            if (result > 0) {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("更改失败，请联系管理员");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("更改失败，请联系管理员");
        }
        return returnObject;
    }


    @RequestMapping("/workbench/activity/exportAllActivitys.do")
    public void filedown(HttpServletResponse response) throws IOException {
        //查询所有的 市场活动信息 ----》使用apache-poi 生成excel文件-----》将生成的excel文件传到客户端
        List<Activity> activityList = activityService.queryAllActivitys();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("市场活动表");
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("活动名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建日期");
        cell = row.createCell(8);
        cell.setCellValue("创建人");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");
        //生成数据行
        Activity activity = new Activity();
        for (int i = 0; i < activityList.size(); i++) {
            activity = activityList.get(i);
            row = sheet.createRow(i + 1);

            cell = row.createCell(0);
            cell.setCellValue(activity.getId());
            cell = row.createCell(1);
            cell.setCellValue(activity.getOwner());
            cell = row.createCell(2);
            cell.setCellValue(activity.getName());
            cell = row.createCell(3);
            cell.setCellValue(activity.getStartDate());
            cell = row.createCell(4);
            cell.setCellValue(activity.getEndDate());
            cell = row.createCell(5);
            cell.setCellValue(activity.getCost());
            cell = row.createCell(6);
            cell.setCellValue(activity.getDescription());
            cell = row.createCell(7);
            cell.setCellValue(activity.getCreateTime());
            cell = row.createCell(8);
            cell.setCellValue(activity.getCreateBy());
            cell = row.createCell(9);
            cell.setCellValue(activity.getEditTime());
            cell = row.createCell(10);
            cell.setCellValue(activity.getEditBy());
        }
//        OutputStream fileOutputStream = new FileOutputStream("F:\\MyCode\\java\\我的项目\\crm-project\\crm\\src\\main\\webapp\\serverDir\\activityList.xls");
//        workbook.write(fileOutputStream);
//        fileOutputStream.close();
//        workbook.close();

        //将生成的excel文件传到客户端
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=activitiesList.xls");
        ServletOutputStream out = response.getOutputStream();
//        FileInputStream is = new FileInputStream("F:\\MyCode\\java\\我的项目\\crm-project\\crm\\src\\main\\webapp\\serverDir\\activityList.xls");
//        byte[] bytes = new byte[128];
//        int len=0;
//        while((len=is.read(bytes))!=-1){
//            out.write(bytes,0,len);
//        }
//        is.close();

        //改进：不用写入到磁盘中，不用生成文件，直接从内存中传输到客户端
        //直接从workbook中向通向浏览器的管道输入
        workbook.write(out);
        workbook.close();
        out.flush();
    }

    @RequestMapping("/workbench/activity/imporActivity.do")
    @ResponseBody
    public  Object imporActivity(MultipartFile activityFile, HttpSession session, String user)  {
        ReturnObject returnObject = new ReturnObject();
        System.out.println(user);
        try {
//            String fileName = activityFile.getOriginalFilename();
//            File file = new File("F:\\资源\\CRM项目\\项目生成文件\\", fileName);
//            activityFile.transferTo(file);  //将数据流转换成文件
//            InputStream is = new FileInputStream("F:\\资源\\CRM项目\\项目生成文件\\" + fileName);  //读取生成的文件流
            //HSSFWorkbook workbook = new HSSFWorkbook(activityFile.getInputStream());
            InputStream is = activityFile.getInputStream();
            HSSFWorkbook workbook = new HSSFWorkbook(is);
            HSSFSheet sheet = workbook.getSheetAt(0);
            HSSFRow row = null;
            HSSFCell cell = null;
            Activity activity=null;
            ArrayList<Activity> activityList = new ArrayList<>();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                //循环行
                activity = new Activity();
                row = sheet.getRow(i);
                activity.setId(UUIDUtils.getUUID());
                User owner=(User)session.getAttribute(Contants.SESSION_USER); //所有者
                activity.setOwner(owner.getId());
                activity.setCreateBy(owner.getId());
                activity.setCreateTime(DateUtils.formateDateTime(new Date()));
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    cell = row.getCell(j);
                    String cellvalue = HSSFUtils.getCellValueForString(cell);
                    switch (j) {
                        case 0:
                            activity.setName(cellvalue);
                            break;
                        case 1:
                            activity.setStartDate(cellvalue);
                            break;
                        case 2:
                            activity.setEndDate(cellvalue);
                            break;
                        case 3:
                            activity.setCost(cellvalue);
                            break;
                        case 4:
                            activity.setDescription(cellvalue);
                            break;
                    }
                }
                activityList.add(activity);
            }
            int i = activityService.saveCreateActivityByList(activityList);
            returnObject.setMessage("成功导入"+i+"条记录");
            returnObject.setRetData(i);
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("添加失败，请联系管理员");
        }
        return returnObject;
    }

    /**
     * 根据传来的 市场活动id  查询 该市场活动的详情，并跳转到detail页面进行显示
     * @param id
     * @return
     */
    @RequestMapping("/workbench/activity/detailActivity.do")
    public String detailActivity(String id ,HttpServletRequest request){
        try {
            List<ActivityRemark> remarkList = activityRemarkService.queryActivityRemarkForDetailByActivityId(id);
            Activity activity = activityService.queryActivityForDatailById(id);
            request.setAttribute("remarkList",remarkList);
            request.setAttribute("activity",activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "workbench/activity/detail";
    }


}








